﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using Citi.PTSConsolidation.Domain;
using Citi.RoutineBase;
using SqlHelper = Citi.PTSConsolidation.Domain.Utils.SqlHelper;

namespace Citi.PTSConsolidation.SchedulerUI
{
    public class GocExtraction : IExecutableRoutine
    {
        public IEnumerable<RoutineParameter> Parameters { get { return null; } }
        private string PtsConnectionString { get { return ConfigurationManager.AppSettings["PtsConnectionString"]; } }
        private string ExcelConnectionString { get { return ConfigurationManager.AppSettings["ExcelConnectionString"]; } }
        private string GocExcelPath { get { return ConfigurationManager.AppSettings["GocExcelPath"]; } }

        public void Start(DateTime scheduledDate, ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            var importedPath = Path.Combine(GocExcelPath, "Imported");

            if (!Directory.Exists(importedPath))
                Directory.CreateDirectory(importedPath);

            currentAction.Description = string.Format("Looking for file in {0}", GocExcelPath);
            var files = Directory.GetFiles(GocExcelPath).Where(x => x.EndsWith(".xlsx"));

            if (!files.Any())
            {
                currentAction.Description = "No files were found. The routine is set as Finished.";
                return;
            }

            foreach (var filePath in files)
            {
                var file = filePath;
                
                currentAction.Description = string.Format("{0} found", Path.GetFileName(file));
                currentAction.Description = "Reading file";

                SqlHelper.CopyExcelToSql(string.Format(ExcelConnectionString, file), Goc.GenerateGocQueryString(),
                    "GOC", PtsConnectionString, Goc.ExcelColumnMappings, string.Empty, true);

                currentAction.Description = "Moving file to import folder";
                var importedFile = Path.Combine(importedPath, Path.GetFileName(file));

                if (File.Exists(importedFile)) File.Delete(importedFile);
                File.Move(file, importedFile);
            }

            currentAction.Description = "Removing duplicated values";
            var deleteDuplicatedQuery = Goc.GenerateDeleteDuplicatedQuery();
            currentAction.Description = deleteDuplicatedQuery;
            SqlHelper.ExecuteReader(deleteDuplicatedQuery, PtsConnectionString);
        }

        public void Stop(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {

        }

        public void Rollback(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {

        }
    }
}
